package cn.qin.xhangapi.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.qin.xhangapi.pojo.SysUsers;
import cn.qin.xhangapi.service.SysUsersService;
import cn.qin.xhangapi.util.md5.MD5Util;
import cn.qin.xhangapi.util.response.ResponseResult;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RequestMapping("/api/profile")
@RestController
public class ProfileController {
    @Resource
    private SysUsersService sysUsersService;

    /**
     * 修改个人信息
     *
     * @author 多仔ヾ
     * @param avatarUrl 账户头像
     * @param realName 真实姓名
     * @return cn.duozai.ct.utils.response.ResponseResult
     */
    @PutMapping("/modifyInfo")
    public ResponseResult modifyInfo(@RequestParam String avatarUrl,
                                     @RequestParam String realName) {
        SysUsers sysUsers = sysUsersService.getById(StpUtil.getLoginIdAsLong());
        sysUsers.setAvatarUrl(avatarUrl);
        sysUsers.setRealName(realName);

        if(sysUsersService.updateById(sysUsers)) {
            return ResponseResult.success("修改成功");
        } else {
            return ResponseResult.failure("修改失败");
        }
    }
    /**
     * 修改账户密码
     *
     * @author 多仔ヾ
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @param rePassword 确认新密码
     * @return cn.duozai.ct.utils.response.ResponseResult
     */
    @PutMapping("/modifyPassword")
    public ResponseResult modifyPassword(@RequestParam String oldPassword,
                                         @RequestParam String newPassword,
                                         @RequestParam String rePassword) {
        // 密码一致性校验
        if(!newPassword.equals(rePassword)) {
            return ResponseResult.failure("两次输入的密码不一致");
        }

        SysUsers sysUsers = sysUsersService.getById(StpUtil.getLoginIdAsLong());

        // 旧密码加密
        String encodeOldPassword = MD5Util.encode(oldPassword, sysUsers.getSalts());

        // 加密后的旧密码不等于数据库存的盐值密码
        if(!encodeOldPassword.equals(sysUsers.getPassword())) {
            return ResponseResult.failure("旧密码错误");
        }

        // 生成随机盐值并存储
        String salt = MD5Util.randSalts(8);
        sysUsers.setSalts(salt);
        // 加密明文密码后存储
        sysUsers.setPassword(MD5Util.encode(newPassword, salt));

        if(sysUsersService.updateById(sysUsers)) {
            StpUtil.logout();
            return ResponseResult.success("修改成功");
        } else {
            return ResponseResult.failure("修改失败");
        }
    }
}
